package com.wudl.windows;

import com.wudl.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.timestamps.AscendingTimestampExtractor;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;


/**
 * @ClassName : Window_EventTime
 * @Description : 窗口的时间函数
 * @Author :wudl
 * @Date: 2020-10-24 15:30
 */

public class WindowEventTime {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // &**** 需要制定时间语义
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
        SingleOutputStreamOperator<WaterSensor> andWatermarks = env.socketTextStream("192.168.1.180", 8899)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] dates = value.split(",");
                        return new WaterSensor(dates[0], Long.valueOf(dates[1]), Integer.valueOf(dates[2]));
                    }
                    // #####TODO 2.指定如何 从数据中 抽取出 事件时间，时间单位是 ms
                }).assignTimestampsAndWatermarks(
                        new AscendingTimestampExtractor<WaterSensor>() {
                            @Override
                            public long extractAscendingTimestamp(WaterSensor elemnet) {
                                return elemnet.getTs() * 100L;
                            }
                        }
                );

//   分组开窗    sensorDS

        andWatermarks.keyBy(data -> data.getId()).timeWindow(Time.seconds(5)).process(
                /**
                 * 全窗口函数：整个窗口的本组数据，存起来，关窗的时候一次性一起计算
                 */
                new ProcessWindowFunction<WaterSensor, Long, String, TimeWindow>() {

                    @Override
                    public void process(String s, Context context, Iterable<WaterSensor> elements, Collector<Long> out) throws Exception {
                        out.collect(elements.spliterator().estimateSize());
                    }
                }
        ).print();

        env.execute();

    }
}
